// miniprogram/pages/myComment/myComment.js
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    comments: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad (options) {
    if (!app.globalData.userInfo) {
      wx.navigateTo({
        url: '/pages/login/login'
      })
    } else {
      this.loadComments()
    }
  },

  onShow () {
    if (app.globalData.userInfo) {
      this.loadComments()
    }
  },

  // 刷新评论
  async loadComments () {
    wx.showLoading({
      title: '评论加载中...'
    })
    const comments = await wx.cloud.callFunction({
      name: 'loadMyComments'
    })
    comments.result.forEach(item => {
      item.createdTime = new Date(item.createdTime).toLocaleString()
    })
    this.setData({
      comments: comments.result
    })
    app.globalData.userInfo.comments = this.data.comments
    wx.hideLoading()
  },

  handleDelete (e) {
    wx.showModal({
      title: '警告',
      content: '确认删除该评论吗？删除后无法恢复！'
    }).then( async res => {
      if (res.cancel) {
        wx.showToast({
          title: '已取消删除',
          icon: 'none'
        })
      } else if (res.confirm) {
        wx.showLoading({
          title: '删除中...'
        })
        const commentInfo = e.currentTarget.dataset.commentInfo
        const { result } = await wx.cloud.callFunction({
          name: 'deleteMyComment',
          data: commentInfo
        })
        if (result.status === 0) {
          this.loadComments()
          wx.showToast({
            title: result.msg,
            icon: 'success'
          })
        } else {
          wx.hideLoading()
        }
      }
    })
  }

})